package com.tencent.qf.team.service.impl;

import com.tencent.qf.team.dao.TyDistributeSaleSharerCommissionBillDao;
import com.tencent.qf.team.dto.db.SalesSharerCommissionBillStatusDo;
import com.tencent.qf.team.dto.db.SharerOutOrderSumDo;
import com.tencent.qf.team.dto.request.SharerOutOrderSumBatchRequest;
import com.tencent.qf.team.dto.request.SharerOutOrderSumForMiniRequest;
import com.tencent.qf.team.dto.request.SharerOutOrderSumRequest;
import com.tencent.qf.team.dto.response.SharerCommissionDBDto;
import com.tencent.qf.team.dto.response.SharerCommissionDto;
import com.tencent.qf.team.dto.response.SharerOutOrderSumBatchDto;
import com.tencent.qf.team.service.SalesSharerCommissionService;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
public class SalesSharerCommissionServiceImpl implements SalesSharerCommissionService {

    @Autowired
    private TyDistributeSaleSharerCommissionBillDao tyDistributeSaleSharerCommissionBillDao;

    /**
     * 查询小b预估佣金-小程序端
     *
     * @param request
     * @return
     */
    @Override
    public SharerCommissionDto sharerCommission(SharerOutOrderSumForMiniRequest request) {
        SharerOutOrderSumDo sharerOutOrderSumDo = this.buildSqlParam(request);
        sharerOutOrderSumDo.setBillStatus(Arrays.asList("WAIT_FOR_SETTLE", "SETTLING", "SETTLE_OK"));

        List<SalesSharerCommissionBillStatusDo> list = tyDistributeSaleSharerCommissionBillDao.commissionBillStatusList(sharerOutOrderSumDo);
        // 根据账单状态,分别统计待确认佣金和预估佣金
        SharerCommissionDto sumDto = this.gatherListByStatus(list);
        return sumDto;
    }

    /**
     * 查询小b预估佣金
     *
     * @param request
     * @return
     */
    @Override
    public SharerCommissionDto sharerOutOrderSum(SharerOutOrderSumRequest request) {
        SharerOutOrderSumDo sharerOutOrderSumDo = this.buildSqlParam(request);

        SharerCommissionDto sumDto = new SharerOutOrderSumBatchDto();
        if (StringUtils.hasText(request.getByBillStatus())) {
            // 场景3
            SharerCommissionDBDto sharerCommissionDBDto = tyDistributeSaleSharerCommissionBillDao.commissionSum(sharerOutOrderSumDo);
            if (sharerCommissionDBDto != null) {
                sumDto.setCommissionAmount(sharerCommissionDBDto.getCommissionAmount());
                sumDto.setRewardAmount(sharerCommissionDBDto.getRewardAmount());
            }
        } else {
            // 场景1&2
            List<SalesSharerCommissionBillStatusDo> list = tyDistributeSaleSharerCommissionBillDao.commissionBillStatusList(sharerOutOrderSumDo);
            // 根据账单状态,分别统计待确认佣金和预估佣金
            sumDto = this.gatherListByStatus(list);
        }
        return sumDto;
    }

    /**
     * 导购助手-批量小B预估收益
     *
     * @param request
     * @return
     */
    @Override
    public List<SharerOutOrderSumBatchDto> sharerOutOrderSumBatch(SharerOutOrderSumBatchRequest request) {
        List<SharerOutOrderSumBatchDto> result = new ArrayList<>();
        for (String uid : request.getUids()) {
            SharerOutOrderSumDo sharerOutOrderSumDo = this.buildSqlParam(request);
            sharerOutOrderSumDo.setUid(uid);

            SharerOutOrderSumBatchDto sumBatchDto = new SharerOutOrderSumBatchDto();
            sumBatchDto.setUid(uid);
            if (StringUtils.hasText(request.getByBillStatus())) {
                // 场景3
                SharerCommissionDBDto sharerCommissionDBDto = tyDistributeSaleSharerCommissionBillDao.commissionSum(sharerOutOrderSumDo);
                if (sharerCommissionDBDto != null) {
                    sumBatchDto.setCommissionAmount(sharerCommissionDBDto.getCommissionAmount());
                    sumBatchDto.setRewardAmount(sharerCommissionDBDto.getRewardAmount());
                }
            } else {
                // 场景1&2
                List<SalesSharerCommissionBillStatusDo> list = tyDistributeSaleSharerCommissionBillDao.commissionBillStatusList(sharerOutOrderSumDo);
                // 根据账单状态,分别统计待确认佣金和预估佣金
                SharerCommissionDto sumDto = this.gatherListByStatus(list);
                BeanUtils.copyProperties(sumDto, sumBatchDto);
            }
            result.add(sumBatchDto);
        }
        return result;
    }

    /**
     * 根据账单状态,分别统计待确认佣金和预估佣金
     *
     * @param list
     * @return
     */
    private SharerCommissionDto gatherListByStatus(List<SalesSharerCommissionBillStatusDo> list) {
        SharerCommissionDto sumDto = new SharerCommissionDto();
        if (!CollectionUtils.isEmpty(list)) {
            list.stream().forEach(e -> {
                if ("SETTLE_OK".equals(e.getBillStatus())) {
                    // 已确认
                    sumDto.setConfirmationCommissionAmount(sumDto.getConfirmationCommissionAmount() + e.getCommissionAmount());
                    sumDto.setConfirmationRewardAmount(sumDto.getConfirmationRewardAmount() + e.getRewardAmount());
                }
                if ("WAIT_FOR_SETTLE".equals(e.getBillStatus()) || "SETTLING".equals(e.getBillStatus())) {
                    // 待确认
                    sumDto.setPendingConfirmationCommissionAmount(sumDto.getPendingConfirmationCommissionAmount() + e.getCommissionAmount());
                    sumDto.setPendingConfirmationRewardAmount(sumDto.getPendingConfirmationRewardAmount() + e.getRewardAmount());
                }
                // 预估
                sumDto.setCommissionAmount(sumDto.getCommissionAmount() + e.getCommissionAmount());
                sumDto.setRewardAmount(sumDto.getRewardAmount() + e.getRewardAmount());
            });
        }
        return sumDto;
    }


    private SharerOutOrderSumDo buildSqlParam(SharerOutOrderSumRequest request) {
        SharerOutOrderSumDo sharerOutOrderSumDo = new SharerOutOrderSumDo();
        BeanUtils.copyProperties(request, sharerOutOrderSumDo);

        if (StringUtils.hasText(request.getStartDate())) {
            long epochMilli = LocalDateTime.parse(request.getStartDate(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")).toInstant(ZoneOffset.of("+8")).toEpochMilli();
            sharerOutOrderSumDo.setStartDate(epochMilli);
        }
        if (StringUtils.hasText(request.getEndDate())) {
            long epochMilli = LocalDateTime.parse(request.getEndDate(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")).toInstant(ZoneOffset.of("+8")).toEpochMilli();
            sharerOutOrderSumDo.setEndDate(epochMilli);
        }

        if (StringUtils.hasText(request.getByBillStatus())) {
            if (ArrayUtils.isNotEmpty(request.getCommissionStatus())) {
                sharerOutOrderSumDo.setCommissionStatus(Arrays.asList(request.getCommissionStatus()));
            } else {
                // 待分配'WAIT_FOR_SETTLE',商家打款'BUSINESS_PAYMENT',平台到账'PLATFORM_ARRIVAL',可结算'CAN_WITHDRAW',已结算'SETTLE_OK',已失效'NOT_VALID'
                sharerOutOrderSumDo.setCommissionStatus(
                        Arrays.asList(new String[]{"WAIT_FOR_SETTLE", "BUSINESS_PAYMENT", "PLATFORM_ARRIVAL", "CAN_WITHDRAW", "SETTLE_OK", "NOT_VALID"}));
            }
        } else {
            // 账单状态
            sharerOutOrderSumDo.setBillStatus(Arrays.asList("WAIT_FOR_SETTLE", "SETTLING", "SETTLE_OK"));
        }

        // 自购&分销
        String[] commissionType = request.getCommissionType();
        if(commissionType != null && commissionType.length > 0){
            List<String> commissionTypes = new ArrayList<>();
            String join = String.join(",", commissionType);
            if (join.contains("SELF_BUY")) {
                commissionTypes.add("SELF_BUY");
            }
            if (join.contains("GUIDE_BUY")) {
                commissionTypes.add("BUYER_DISTRIBUTION");
                commissionTypes.add("GUIDER_DISTRIBUTION");
                commissionTypes.add("GUIDE_BUY");
                commissionTypes.add("SHARE_DISTRIBUTION");
            }
            sharerOutOrderSumDo.setCommissionTypeList(commissionTypes);
        }

        return sharerOutOrderSumDo;

    }

    private SharerOutOrderSumDo buildSqlParam(SharerOutOrderSumForMiniRequest request) {
        SharerOutOrderSumDo sharerOutOrderSumDo = new SharerOutOrderSumDo();
        BeanUtils.copyProperties(request, sharerOutOrderSumDo);

        // 自购&分销
        List<String> commissionTypes = new ArrayList<>();
        String[] commissionType = request.getCommissionType();
        if (commissionType != null) {
            String join = String.join(",", commissionType);
            if (join.contains("SELF_BUY")) {
                commissionTypes.add("SELF_BUY");
            }
            if (join.contains("GUIDE_BUY")) {
                commissionTypes.add("BUYER_DISTRIBUTION");
                commissionTypes.add("GUIDER_DISTRIBUTION");
                commissionTypes.add("GUIDE_BUY");
                commissionTypes.add("SHARE_DISTRIBUTION");
            }
        }
        sharerOutOrderSumDo.setCommissionTypeList(commissionTypes);

        if (StringUtils.hasText(request.getStartDate())) {
            long epochMilli = LocalDateTime.parse(request.getStartDate(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")).toInstant(ZoneOffset.of("+8")).toEpochMilli();
            sharerOutOrderSumDo.setStartDate(epochMilli);
        }
        if (StringUtils.hasText(request.getEndDate())) {
            long epochMilli = LocalDateTime.parse(request.getEndDate(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")).toInstant(ZoneOffset.of("+8")).toEpochMilli();
            sharerOutOrderSumDo.setEndDate(epochMilli);
        }
        return sharerOutOrderSumDo;
    }
}
